//
//  devSearch.m
//  serialTest
//
//  Created by mt-007 on 2021/3/20.
//

#import "devSearch.h"

@implementation devSearch

/**
 * @param posPath open path usually is /dev .
 * @return An directory，key is device number, value is device name.
 *
 * @brief Get all device name from path.
 */
+ (NSDictionary *)searchDevice:(NSString *) posPath{
    NSString *path = posPath;
    NSFileManager *serialFileManager = [NSFileManager defaultManager];
    NSDirectoryEnumerator *devDirectoryEnumerator;
    devDirectoryEnumerator = [serialFileManager enumeratorAtPath:path];
    
    // create empty dictionary.
    NSMutableDictionary *fileDic = [NSMutableDictionary dictionary] ;
    // create pre name of dev
    NSString *preName = @"device";
    
    // Counting starts at 1, not 0.
    int ordName = 1;
    while((path=[devDirectoryEnumerator nextObject])!=nil) {
        // use regex to find the serial port file. Prefix is [tty.] or [cu.] as usual, we use [tty.] file.
        NSString *regex = @"^tty.+([a-zA-Z]+-?)+[a-zA-Z0-9+-?]";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        
        BOOL isValid = [predicate evaluateWithObject:path];
        if(isValid == YES){
            // key - value : insertKey - returnPath.
            NSMutableString *insertKey = [[NSMutableString alloc] initWithString:preName];
            NSMutableString *returnPath = [[NSMutableString alloc] initWithString:posPath];
            
            [insertKey appendString:[NSString stringWithFormat:@"%d", ordName]];
            [returnPath appendString:path];
            
            ordName++;
            
            [fileDic setValue:returnPath forKey: insertKey];
        }
    }
    return fileDic;
}

@end
